//
//  ContactViewController.m
//  RZIM
//
//  Created by reyzhang on 2021/8/12.
//

#import "ContactViewController.h"
#import <Masonry/Masonry.h>
#import <UIKit/UIKit.h>
#import "ContactTableCell.h"
#import "UIViewController+HUD.h"
#import "RZSlideMenuView.h"
#import "AddFriendViewController.h"
#import "NewFriendViewController.h"
#import "ChatConversationViewController.h"
#import "CreateGroupViewController.h"

@interface ContactViewController () <UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *moreBtn;
@property (nonatomic, strong) NSArray *resultKeys;
@property (nonatomic, strong) NSDictionary *resultSectionDict;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic, strong) RZSlideMenuView *menuView;
@property (nonatomic,strong)NSIndexPath *lastIndexPath;
@property (nonatomic,strong)NSString *friendId;
@property (nonatomic,strong)NSString *friendName;
@property (nonatomic,strong)UIImageView *emptyImageView;
@property (nonatomic,strong)UILabel *emptyLabel;
@property (nonatomic,strong)UIButton *bageButton;
@end

@implementation ContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    [self loadData];
    [self loadBageData];
    [self initSearchBar];
    if (!self.showSelect == YES) {
        
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.moreBtn];
        self.navigationItem.rightBarButtonItem = right;
    }
    [self setEmptyView];
    self.dataArray = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:@"DeleteFriend" object:nil];
    
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"DeleteFriend" object:nil];
    
}
- (void)initView {
    [self.view addSubview:self.tableView];
    
    CGRect tableFrame = self.tableView.frame;
    
    CGFloat removeHeight = (!self.hidesBottomBarWhenPushed ? self.tabBarController.tabBar.frame.size.height : 0);
    tableFrame.size.height -= removeHeight;
    
    if (@available(iOS 11.0, *)) {
        CGFloat adjustTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top == 0 ? 0 : 20;
        CGFloat removeHeight = [YMIMKitUtils isHairHead]  ? 64 + adjustTop : 64;
        tableFrame.size.height -= removeHeight;
    } else {
        tableFrame.size.height -= 64;
    }
    self.tableView.frame = tableFrame;
    
    self.tableView.allowsMultipleSelection = self.showSelect;
    if(self.showSelect) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                                  initWithCustomView:self.confirmBtn];
    }
}

-(void)initSearchBar{
    
    UIView *newFreindView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
    newFreindView.backgroundColor = [UIColor whiteColor];
    if (!self.showSelect==YES) {
        
        self.tableView.tableHeaderView = newFreindView;
    }
    
    UIButton *newFriendButton = [[UIButton alloc]init];
    [newFriendButton setImage:[UIImage imageNamed:@"New_Friend"] forState:UIControlStateNormal];
    [newFriendButton setTitle:@"    新的好友" forState:UIControlStateNormal];
    [newFriendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [newFriendButton addTarget:self action:@selector(newFriendAction) forControlEvents:UIControlEventTouchUpInside];
    newFriendButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [newFreindView addSubview:newFriendButton];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(newFriendAction)];
    newFreindView.userInteractionEnabled = YES;
    [newFreindView addGestureRecognizer:tap];
    [newFriendButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_equalTo(newFreindView.mas_left).offset(15);
        make.centerY.mas_equalTo(newFreindView.mas_centerY);
        
    }];
    UIView *lineView= [[UIView alloc]init];
    lineView.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
    [newFreindView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width);
        make.height.mas_equalTo(2);
        make.top.mas_equalTo(newFreindView.mas_bottom).offset(-2);
        
    }];
    [newFriendButton addSubview:self.bageButton];
    [self.bageButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_equalTo(newFriendButton.mas_right).offset(1);
        make.top.mas_equalTo(newFriendButton.mas_top);
        make.size.mas_equalTo(CGSizeMake(15, 15));
        
    }];
    self.bageButton.layer.cornerRadius = 7.5;
    self.bageButton.hidden = YES;
    
}

-(void)setEmptyView{
    
    self.emptyImageView = [[UIImageView alloc]init];
    [self.emptyImageView setImage:[UIImage imageNamed:@"Contact_Null"]];
    [self.view addSubview:self.emptyImageView];
    [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
    
        make.top.mas_equalTo(self.view.mas_top).offset(SCREEN_HEIGHT/2-100);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(100);
    
    }];
    self.emptyImageView.hidden = YES;
   
    self.emptyLabel= [[UILabel alloc] init];
    self.emptyLabel.text = @"暂无好友";
    [self.emptyLabel setFont:YMFont(14)];
    [self.emptyLabel setTextColor:[UIColor lightGrayColor]];
    self.emptyLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.emptyLabel];
    [self.emptyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    
         make.top.mas_equalTo(self.emptyImageView.mas_bottom).offset(5);
         make.centerX.mas_equalTo(self.emptyImageView.mas_centerX);
    
    }];
    self.emptyLabel.hidden = YES;
    
}

-(void)newFriendAction{

    NewFriendViewController *vc = [[NewFriendViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [vc setHandleBlock:^{

        [self loadData];
        [self loadBageData];
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loadData {
    
    [[YMIMClient sharedClient].friendManager getFriendsListWithCompletion:^(NSArray<YMFriendInfo *> * _Nonnull friendsList, YMErrorCode code) {
        
        [self.dataArray removeAllObjects];
        for (int i = 0; i<friendsList.count; i++) {
            
            YMFriendInfo *info = friendsList[i];
            [self.dataArray addObject:info];
            
        }
        if (self.dataArray.count==0) {
            
            self.emptyImageView.hidden = NO;
            self.emptyLabel.hidden = NO;
            self.tableView.scrollEnabled = NO;
            
        }else{
            
            self.emptyImageView.hidden = YES;
            self.emptyLabel.hidden = YES;
            self.tableView.scrollEnabled = YES;
        }
        [self sortAndRefreshWithList:self.dataArray];

    }];

}

-(void)loadBageData{
    
    [[YMIMClient sharedClient].friendManager getFriendsApplyListWithPage:1 pageSize:20 completion:^(NSArray<YMFriendApplyInfo *> * _Nonnull applyList, YMErrorCode code) {
//        utState
//        申请状态 1申请中 2已添加 3已拒绝
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i<applyList.count; i++) {
            
            YMFriendApplyInfo *info = applyList[i];
            if (info.applyState == 1) {
                
                [array addObject:info];
            }
            
        }
        NSString *num = [NSString stringWithFormat:@"%ld",array.count];
        if (array.count>0) {
            
            self.bageButton.hidden = NO;
            [self.bageButton setTitle:num forState:UIControlStateNormal];
            
        }else{
            
            self.bageButton.hidden = YES;
        }
     
    }];

}
- (void)sortAndRefreshWithList:(NSArray *)friendList {
    NSDictionary *resultDic = [[YMIMKitUtils sortedArrayWithPinYinDic:friendList] copy];
   
    self.resultKeys = resultDic[@"allKeys"];
    self.resultSectionDict = resultDic[@"infoDic"];
    [self.tableView reloadData];
}



/**
 确认选择
 */
- (void)confirmAction {
    NSArray *indexArray = self.tableView.indexPathsForSelectedRows;
    if (self.showSingleSelect == YES) {
        if (self.friendId == nil||[self.friendId isEqualToString:@""]) {
            
            [self showHint:@"至少选择一个好友"];
            return;
        }
        ChatConversationViewController *vc = [[ChatConversationViewController alloc] initWithConversationType:0 targetId:self.friendId];
        vc.hidesBottomBarWhenPushed = YES;
        vc.title = self.friendName;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    if (indexArray.count == 0) {
        [self showHint:@"请选择联系人"];
        return;
    }
    
    NSMutableArray *userArray = @[].mutableCopy;
    for (int i= 0; i<indexArray.count; i++) {
        NSIndexPath *indexPath = indexArray[i];
        
        NSString *letter = self.resultKeys[indexPath.section];
        NSArray *array = self.resultSectionDict[letter];
        
        
        YMFriendInfo *userInfo = array[indexPath.row];
        [userArray addObject:userInfo.friendId];
        
    }
    
    !self.didSelectResultBlock ?: self.didSelectResultBlock(userArray);
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.resultKeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *letter = self.resultKeys[section];
    NSInteger rows = [self.resultSectionDict[letter] count];
    return rows;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ContactTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactTableCell" forIndexPath:indexPath];
    NSString *letter = self.resultKeys[indexPath.section];
    NSArray *array = self.resultSectionDict[letter];
    YMUserInfo *userInfo = array[indexPath.row];
    [cell bindData:userInfo];
    cell.showSelect = self.showSelect;
    cell.showSingleSelect = self.showSingleSelect;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 56;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!self.showSelect == YES) {

     
        NSString *letter = self.resultKeys[indexPath.section];
        NSArray *array = self.resultSectionDict[letter];
        YMFriendInfo *userInfo = array[indexPath.row];
    
        ChatConversationViewController *vc = [[ChatConversationViewController alloc] initWithConversationType:0 targetId:userInfo.friendId];
        vc.hidesBottomBarWhenPushed = YES;
        vc.title = userInfo.friendName;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    if (self.showSingleSelect == YES) {
        
        ContactTableCell *cell = [tableView cellForRowAtIndexPath:_lastIndexPath];
        cell.checkBtn.selected = NO;
        _lastIndexPath = indexPath;
        ContactTableCell *celled = [tableView cellForRowAtIndexPath:indexPath];
        celled.checkBtn.selected = YES;
        NSString *letter = self.resultKeys[indexPath.section];
        NSArray *array = self.resultSectionDict[letter];
        YMFriendInfo *userInfo = array[indexPath.row];
        self.friendId = userInfo.friendId;
        self.friendName = userInfo.friendName;
        [tableView reloadData];
    }
    

}

#pragma mark tableview滑动删除
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return UITableViewCellEditingStyleDelete;
 
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //只要实现这个方法，就实现了默认滑动删除！！！！！
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {

        NSString *letter = self.resultKeys[indexPath.section];
        NSArray *array = self.resultSectionDict[letter];
        YMFriendInfo *userInfo = array[indexPath.row];
        [[YMIMClient sharedClient].friendManager deleteFriendWithFriendId:userInfo.friendId completion:^(YMErrorCode code) {
            
            [self showHint:@"删除成功"];
            [self loadData];
            
        }];
    }
}


-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 32.f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, self.view.frame.size.width, 32);
    view.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectZero];
    title.frame = CGRectMake(13, 8, 15, 16);
    title.font = [UIFont systemFontOfSize:14.f];
    title.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];;
    [view addSubview:title];
    title.text = self.resultKeys[section];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}
/**
 显示索引标题
 */
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.resultKeys;
}

#pragma mark Private method
- (void)openMenu:(id)sender  {
    RZSlideMenuConfig *config = [[RZSlideMenuConfig alloc] init];
    config.direction = DirectionFromRight;
    self.menuView = [[RZSlideMenuView alloc] initWithConfig:config];
    
    RZSlideMenuModel *chat = [RZSlideMenuModel createWithIcon:@"Menu_Chat" name:@"发起会话"];
    RZSlideMenuModel *addfriend = [RZSlideMenuModel createWithIcon:@"Menu_Add" name:@"添加好友"];
    RZSlideMenuModel *groupchat = [RZSlideMenuModel createWithIcon:@"Menu_GroupChat" name:@"发起群聊"];
    RZSlideMenuModel *roomchat = [RZSlideMenuModel createWithIcon:@"Menu_GroupChat" name:@"新建聊天室"];
    self.menuView.menuArray = @[chat,addfriend,groupchat,roomchat];
    
    [self.menuView showWithAnimation:YES];
    __weak __typeof(self) weakSelf = self;
    
    self.menuView.selectMenuAtIndex = ^(NSInteger index, RZSlideMenuModel * _Nonnull model) {
        [weakSelf handlerSlideMenuAtIndex:index];
    };
}


/**
 处理侧滑菜单
 */
- (void)handlerSlideMenuAtIndex:(NSInteger)index {
    if (index == 0) {
        
        ContactViewController *vc = [[ContactViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.showSelect = YES;
        vc.showSingleSelect = YES;
        vc.title = @"发起会话";
        vc.didSelectResultBlock = ^(NSArray * _Nonnull userArray) {
            UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            CreateGroupViewController *vc = [main instantiateViewControllerWithIdentifier:@"CreateGroupViewController"];
            vc.hidesBottomBarWhenPushed = YES;
            vc.uidsList = userArray;
            [self.navigationController pushViewController:vc animated:YES];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 1){
        
        AddFriendViewController *vc = [[AddFriendViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (index==2){
        
        ContactViewController *vc = [[ContactViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.showSelect = YES;
        vc.title = @"发起群聊";
        vc.didSelectResultBlock = ^(NSArray * _Nonnull userArray) {
            UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            CreateGroupViewController *vc = [main instantiateViewControllerWithIdentifier:@"CreateGroupViewController"];
            vc.hidesBottomBarWhenPushed = YES;
            vc.uidsList = userArray;
            vc.title = @"创建群聊";
            [self.navigationController pushViewController:vc animated:YES];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==3){
        
        ContactViewController *vc = [[ContactViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.showSelect = YES;
        vc.title = @"新建聊天室";
        vc.didSelectResultBlock = ^(NSArray * _Nonnull userArray) {
            UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            CreateGroupViewController *vc = [main instantiateViewControllerWithIdentifier:@"CreateGroupViewController"];
            vc.hidesBottomBarWhenPushed = YES;
            vc.uidsList = userArray;
            vc.title = @"新建聊天室";
            vc.creteType = RoomType;
            [self.navigationController pushViewController:vc animated:YES];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[ContactTableCell class] forCellReuseIdentifier:@"ContactTableCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (UIButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1] forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _confirmBtn.frame = CGRectMake(0, 0, 44, 44);
        [_confirmBtn addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}
-(UIButton *)bageButton{
    
    if (_bageButton == nil) {
        
        _bageButton = [[UIButton alloc]init];
        _bageButton.backgroundColor = [UIColor redColor];
        [_bageButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _bageButton.titleLabel.font = [UIFont systemFontOfSize:12];
        
    }
    
    return _bageButton;
}
- (UIButton *)moreBtn {
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreBtn setImage:[UIImage imageNamed:@"Message_Plus"] forState:UIControlStateNormal];
        _moreBtn.frame = CGRectMake(0, 0, 40, 40);
        [_moreBtn addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtn;
}
@end
